<template>
  <div>
    <div class="search">
      <input
        v-model="keyword"
        class="search-input"
        type="text"
        placeholder="输入城市名或拼音"
      />
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li
          class="search-item border-bottom"
          v-for="item of list"
          :key="item.id"
          @click="handleCityClick(item.name)"
        >
          {{ item.name }}
        </li>
        <li class="search-item border-bottom" v-show="hasNodata">
          没有找到匹配数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from "better-scroll";
import axios from "axios";

export default {
  name: "CitySearch",
  data() {
    return {
      cities: {},
      keyword: "",
      list: [],
      timer: null,
    };
  },
  methods: {
    loadCities() {
      axios
        .get(" http://localhost:3000/cities")
        .then((res) => {
          this.cities = res.data;
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleCityClick(city) {
      // this.$store.dispatch("changeCity", city);
      // 可以不用dispatch，直接使用commit，调用mutation
      this.$store.commit("changeCity", city);

      // 编程式导航，当点击了城市之后，直接回到首页
      this.$router.push("/");
    },
  },
  mounted() {
    this.loadCities();
    this.scroll = new Bscroll(this.$refs.search);
  },
  watch: {
    keyword() {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      if (!this.keyword) {
        this.list = [];
        return;
      }
      this.timer = setTimeout(() => {
        const result = [];
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (
              value.spell.indexOf(this.keyword) > -1 ||
              value.name.indexOf(this.keyword) > -1
            ) {
              result.push(value);
            }
          });
        }
        this.list = result;
      }, 100);
    },
  },
  computed: {
    hasNodata() {
      return !this.list.length;
    },
  },
};
</script>

<style lang='stylus' scoped>
.search {
  height: 0.62rem;
  padding: 0.1rem;
  background: #00bcd4;
}

.search-input {
  width: 100%;
  height: 0.62rem;
  line-height: 0.62rem;
  text-align: center;
  border-radius: 0.06rem;
  border: 0.01rem;
  color: #666;
  font-size: 0.3rem;
}

.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  top: 1.58rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #eee;
}

.search-item {
  line-height: 0.62rem;
  padding-left: 0.2rem;
  color: #666;
  background-color: #fff;
}
</style>